<!--
 * @Descripttion: 菜单的新增和编辑
 * @version:
 * @Author: wl
 * @Date: 2020-05-25 11:30:38
 * @LastEditors: wl
 * @LastEditTime: 2020-08-20 19:34:57
-->
<template>
  <div>
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="80px"
      style="text-align: left"
    >
      <el-form-item label="菜单名称" prop="title">
        <el-input v-model="dataForm.title" placeholder="菜单名称"></el-input>
      </el-form-item>
      <el-form-item label="菜单路由" prop="url">
        <el-row>
          <el-col :span="22">
            <el-input v-model="dataForm.url" placeholder="菜单路由"></el-input>
          </el-col>
          <el-col :span="2" class="icon-list__tips">
            <el-tooltip placement="top" effect="light" style="padding: 10px">
              <div slot="content">
                <p>URL格式：</p>
                <p>
                  1.常规业务开发的功能URL，如用户管理，Views目录下页面路径为
                  /Sys/User, 此处填写 /sys/user。
                </p>
                <p>
                  2.嵌套外部网页，如通过菜单打开百度网页，此处填写
                  http://www.baidu.com，http:// 不可省略。
                </p>
                <p>
                  示例：用户管理：/sys/user 嵌套百度：http://www.baidu.com
                  嵌套网页：http://127.0.0.1:8000
                </p>
              </div>
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="菜单分类" prop="type">
        <el-select v-model="dataForm.type" clearable placeholder="请选择">
          <el-option
            v-for="item in dictListType"
            :key="item._id"
            :label="item.name"
            :value="item.DID"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜单位置" prop="position">
        <el-select
          v-model="dataForm.position"
          clearable
          placeholder="请选择"
          @change="change"
        >
          <el-option
            v-for="item in dictList"
            :key="item._id"
            :label="item.name"
            :value="item.DID"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜单模块" prop="modular" v-if="isShow || dataForm.modular">
        <el-select v-model="dataForm.modular" clearable placeholder="请选择">
          <el-option
            v-for="item in dictListModular"
            :key="item._id"
            :label="item.name"
            :value="item.DID"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- tableData -->
      <el-form-item v-if="dataForm.PID" label="上级菜单" prop="PID">
        <el-select v-model="dataForm.PID" clearable placeholder="请选择">
          <el-option
            v-for="item in tableData"
            :key="item._id"
            :label="item.title"
            :value="item.WID"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权限控制" prop="codes">
        <el-select
          v-model="dataForm.codes"
          multiple
          clearable
          collapse-tags
          placeholder="请选择"
        >
          <el-option
            v-for="item in villageList"
            :key="item._id"
            :label="item.name"
            :value="item.CID"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序编号" prop="sort">
        <el-input-number
          v-model="dataForm.sort"
          controls-position="right"
          :min="0"
          label="排序编号"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="菜单图标" prop="cover">
      <div>
          <el-upload
          ref="uploadImg"
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
           :beforeUpload="beforeAvatarUpload"
          :http-request="uploadPicturePosta"
        >
          <img
            v-if="dataForm.cover"
            :src="getItemPhoto(dataForm.cover)"
            class="avatar"

          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
     
        <!-- <i style="color: red">*图标必须上传</i> -->
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="dataForm.remarks" placeholder="备注信息"></el-input>
      </el-form-item>
      <el-form-item label="颜色" prop="color">
        <el-input v-model="dataForm.color" placeholder="颜色"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('dataForm')"
          >提交</el-button
        >
        <!-- <el-button @click="resetForm()">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import FaIconTooltip from "@/components/FaIconTooltip";
import fileUtils from "@/utils/fileUtils.js";
export default {
  components: {
    PopupTreeInput,
    FaIconTooltip,
  },
  props: {
    dataForm: {
      type: Object,
      default: function () {
        return {
          title: "", //标题
          cover: "", //封面
          sort: "", //排序
          type: "", //类型（读字典）
          position: "", //位置（读字典）
          modular: "", //模块（读字典）
          remarks: "", //（备注）
          codes: [], //（权限控制的小区id数组）
          // DTID: "", //（类型id 党建、服务这些）
          url: "", // （小程序路由）,
          color:"",
        };
      },
    },
    tableData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    childAdd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      editLoading: false,
      menuTypeList: ["目录", "菜单"],
      popupTreeData: [],
      popupTreeProps: {
        label: "name",
        children: "children",
      },
      dataRule: {
        title: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
      },
      dictList: [], //菜单位置
      dictListType: [], //菜单类型
      dictListModular: [], //菜单模块 民生、党建
      isShow: false, // 是否显示菜单模块
      villageList: [],
      addImgUrl: "",
    };
  },
  methods: {
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + "avatar/" + id;
      return url;
    },
      beforeAvatarUpload(file) {

      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isLt2M) {
        this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "warning",
        });
      }
      return isLt2M;

    },
    // 菜单位置改变事件
    change(e) {
      if (e && e == "41c74f61-2fc7-4161-afe2-44469ed0ce46") {
        this.isShow = true;
      }else{
        this.isShow = false

      }
    },
    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },

    // 编辑添加图片
    async uploadPicturePosta(param) {
      var imgup = "";

      await this.getBase64(param.file).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup,
      };
      // this.$http
      this.$api.imgAdd.addimgPer(paramd).then((res) => {
        this.imgURL = res.data;
        this.dataForm.cover = res.id;
      });

      // this.$api.imgAdd.addimgPer(paramd).then((res) => {
      //   this.imgURL = res.data;
      //   this.form.cover = res.id;
      // });
    },

    // 表单提交
    submitForm(formName) {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            var aaa = JSON.stringify(params);
            this.$api.menu.sys_weCatMenu_add(aaa).then((res) => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({ message: "操作成功", type: "success" });
                this.$emit("handleSave");
                this.$refs[formName].resetFields();

                // this.$refs["dataForm"].resetFields();
                // this.dialogVisible = false;
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
            });
          });
        }
      });
    },
    handleClose() {
      this.$emit("closeEdit");
    },
  },
  mounted() {
    this.dictList = JSON.parse(
      sessionStorage.getItem("dictData")
    ).applet_menu_type;

    this.dictListType = JSON.parse(
      sessionStorage.getItem("dictData")
    ).applet_menuClassification_type;

    this.dictListModular = JSON.parse(
      sessionStorage.getItem("dictData")
    ).applet_modular_type;
    this.villageList = this.$store.state.village.villageList;
  },
};
</script>

<style lang='scss' scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;



}
</style>
